package com.mp.approvalreq.service.impl;


import com.mp.approvalreq.dao.TemplateDao;
import com.mp.approvalreq.dao.impl.TemplateDaoImpl;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.ApprovalForTaskServiceServant;
import com.mp.approvalreq.util.DbName;
import com.mp.approvalreq.util.ErrorUtils;
import com.mp.approvalreq.util.ListHelper;
import com.mp.approvalreq.util.LookAuth;
import com.mp.user.entity.User;
import com.mp.user.util.UserUtils;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.jdbc.util.DBUtils;
import com.plusmoney.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.List;


public class ApprovalForTaskServantImpl implements ApprovalForTaskServiceServant {

	private static final Logger logger = LoggerFactory.getLogger(ApprovalForTaskServantImpl.class);

	@Override
	public List<Integer> getWhatICanSeeInApprovalIds(List<Integer> requestIds, User user, List<Integer> myBoys) throws Throwable {
		Connection connection = DBUtils.getConnection(DbName.APPROVALREQ);
		try {
			check(requestIds, user);
			if (UserUtils.isAdmin(user) || UserUtils.isVicePresident(user)) {
				return requestIds;
			}

			TemplateDao templateDao = new TemplateDaoImpl(connection);

			List<Request> requests = templateDao.getAllPeopleOfApproval(requestIds);

			List<Integer> resultRequestIds = new LinkedList<>();
			for (Request request : requests) {
				if (LookAuth.checkUserIsCanSeeRequest(user, request)) {
					resultRequestIds.add(request.getRequestDkey());
				}
			}

			return resultRequestIds;
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
			throw ErrorUtils.throwError(e);
		} finally {
			DBUtils.release(connection);
		}
	}

	private void check(List<Integer> requestIds, User user) {
		if (ListHelper.isNullEmpty(requestIds)) {
			throw new RpcServerLogicalException(1, "审批id集合为空");
		}

		if (Utils.isNull(user)) {
			throw new RpcServerLogicalException(1, "用户为空");
		}

		logger.info("审批id集合:" + requestIds + " user信息:" + user.getContactName() + " cid:" + user.getContactId());
	}
}
